angular.module('inspinia').controller('agentActivitySaveCtrl',function($scope,$http,i18nService,SweetAlert,$document,$state,$stateParams){
    i18nService.setCurrentLang('zh-cn');  //设置语言为中文
    $scope.paginationOptions=angular.copy($scope.paginationOptions);

    $scope.isDetail=$stateParams.isDetail=="1";

    $scope.actTypeSelect = [{text:"全部",value:""},{text:"百团大战",value:"1"},{text:"千团大战",value:"2"}];
    $scope.actTypeStr=angular.toJson($scope.actTypeSelect);

    $scope.openStatusSelect = [{text:"全部",value:null},{text:"打开",value:1},{text:"关闭",value:1}];
    $scope.openStatusStr=angular.toJson($scope.openStatusSelect);

    $scope.agentSelect = [{text:"所有代理商",value:"ALL"}];
    $scope.agent="ALL"



    //初始化数据
    $scope.initData=function(){
        if($stateParams.actCode==null || $stateParams.actCode==undefined || $stateParams.actCode==="-1"){
            $scope.addInfo={openStatus:null,actBeginTime:null,actEndTime:null};
            //默认数据2条
            $scope.addInfo.detailList=[
                {status:"0",actType:"1",actStr:"参与商户数（直属）≥ x 人，牛气值排名前x名"},
                {status:"0",actType:"2",actStr:"壕气值排名x名"}
            ];
            $scope.result=$scope.addInfo.detailList;
        }else{
            $scope.getInfo($stateParams.actCode);
        }

    };
    $scope.getInfo=function(actCode){
        $http.post("agentActivityAction/getAgentActivity", "actCode="+actCode,
            {headers: {'Content-Type': 'application/x-www-form-urlencoded'}})
            .success(function(data){
                if(data.status){
                    $scope.addInfo=data.info;
                    $scope.addInfo.actBeginTime=$scope.addInfo.actBeginTime==null?null:moment($scope.addInfo.actBeginTime).format('YYYY-MM-DD HH:mm:ss');
                    $scope.addInfo.actEndTime=$scope.addInfo.actEndTime==null?null:moment($scope.addInfo.actEndTime).format('YYYY-MM-DD HH:mm:ss');

                    if($scope.addInfo.detailList!=null&&$scope.addInfo.detailList.length>0){
                        for(var i=0;i<$scope.addInfo.detailList.length;i++){
                            var item=$scope.addInfo.detailList[i];
                            if(item.actType=="1"){
                                if(item.activeExt!=null&&item.activeExt!=undefined&&item.activeExt!==""){
                                    var json=JSON.parse(item.activeExt);
                                    item.actStr="参与商户数（直属）≥ "+json.merchantNum+" 人，牛气值排名前"+json.aatTop+"名";
                                }else{
                                    item.actStr="参与商户数（直属）≥ x 人，牛气值排名前x名";
                                }
                            }else{
                                if(item.activeExt!=null&&item.activeExt!=undefined&&item.activeExt!==""){
                                    var json=JSON.parse(item.activeExt);
                                    item.actStr="壕气值排名"+json.aatTop+"名";
                                }else{
                                    item.actStr="壕气值排名名";
                                }
                            }
                        }
                    }else{
                        //默认数据2条
                        $scope.addInfo.detailList=[
                            {status:"0",actType:"1",actStr:"参与商户数（直属）≥ x 人，牛气值排名前x名"},
                            {status:"0",actType:"2",actStr:"壕气值排名x名"}
                        ];
                    }
                    $scope.result=$scope.addInfo.detailList;
                }
            });
    }

    $scope.initData();


    $scope.userGrid={                           //配置表格
        data: 'result',
        paginationPageSize:10,                  //分页数量
        paginationPageSizes: [10,20,50,100],	//切换每页记录数
        useExternalPagination: true,		    //开启拓展名
        enableHorizontalScrollbar: true,        //横向滚动条
        enableVerticalScrollbar : true,  		//纵向滚动条
        columnDefs:[                           //表格数据
            {field: 'status',displayName: '选择',width: 180,cellTemplate:
                    '<input type="checkbox" ng-disabled="grid.appScope.isDetail" ng-checked="row.entity.status==1" ng-model="row.entity.status"  ng-true-value="1" ng-false-value="0"/>'
            },
            { field: 'actType',displayName:'活动类型',width:180,cellFilter:"formatDropping:" +  $scope.actTypeStr },
            { field: 'actStr',displayName:'榜单规则',width:450},
            { field: 'id',displayName:'操作',width:180,cellTemplate:
                    '<div class="lh30">'+
                        '<a target="_blank" ng-click="grid.appScope.toActivityDetail(row.entity,1)">详情 </a> ' +
                        '<a target="_blank" ng-show="!grid.appScope.isDetail" ng-click="grid.appScope.toActivityDetail(row.entity,2)"> | 修改</a> ' +
                    '</div>'
            }
        ]
    };
    $scope.submitting=false;
    $scope.saveInfo=function(){
        if($scope.addInfo.actBeginTime==null||$scope.addInfo.actBeginTime=="" ||$scope.addInfo.actEndTime==null||$scope.addInfo.actEndTime==""){
            $scope.notice("活动时间不能为空!");
            return;
        }
        if ($scope.submitting) {
            return;
        }
        $scope.submitting = true;
        var data = {
            info:angular.toJson($scope.addInfo)
        };
        var url;
        var isAdd=0;
        if($scope.addInfo.actCode!=null&&$scope.addInfo.actCode!=undefined&&$scope.addInfo.actCode!==""){
            url="agentActivityAction/editAgentActivity";//修改
        }else{
            url="agentActivityAction/addAgentActivity";//新增
            isAdd=1;
        }
        $http.post(url,data,$scope.postCfgAllCurrency)
            .success(function (data) {
                $scope.notice(data.msg);
                if (data.status) {
                    if(isAdd==1){
                        $scope.getInfo(data.actCode);
                    }
                }
                $scope.submitting = false;
            }).error(function(data){
                $scope.notice(data.msg);
                $scope.submitting = false;
            });
    };

    $scope.toBack=function(){
        $state.transitionTo('agent.agentActivityQuery',null,{reload:true});
    }
    /**
     * 子活动界面
     */
    $scope.toActivityDetail=function(entity,isDetail){
        if(entity.actCode!=null && entity.actCode!=undefined && entity.actCode!==""
            && entity.actDetCode!=null && entity.actDetCode!=undefined && entity.actDetCode!==""
        ){
            if(!$scope.isDetail&&isDetail==1){
                $state.transitionTo('agent.agentActivityDetailSave',{actCode:entity.actCode,actDetCode:entity.actDetCode,isDetail:3},{reload:true});
            }else{
                $state.transitionTo('agent.agentActivityDetailSave',{actCode:entity.actCode,actDetCode:entity.actDetCode,isDetail:isDetail},{reload:true});
            }
        }else{
            $scope.notice("请先保存代理商活动基础配置!");
        }
    }

    /**
     *富文本框按钮控制
     */
    $scope.summeroptions = {
        toolbar: [
            ['style', ['bold', 'italic', 'underline','clear']],
            ['fontface', ['fontname']],
            ['textsize', ['fontsize']],
            ['fontclr', ['color']],
            ['alignment', ['ul', 'ol', 'paragraph', 'lineheight']],
            ['height', ['height']],
            ['insert', ['hr']],
            // ['insert', ['link','picture','video','hr']],
            ['view', ['codeview']]
        ]
    };

}).filter('trustHtml', function ($sce) {
    return function (input) {
        return $sce.trustAsHtml(input);
    }
});